<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="实现Raft协议：Part 3 - 持久性和优化, 码道诚公">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="baidu-site-verification" content="code-oqVlgh2wQV" />
    <meta name="google-site-verification" content="Z-8Fm46WY6NL_3kxilmoqToW4jnvyF7boTgciTLBXUs" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>实现Raft协议：Part 3 - 持久性和优化 | 码道诚公</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="码道诚公" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">码道诚公</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">码道诚公</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">实现Raft协议：Part 3 - 持久性和优化</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                                <span class="chip bg-color">分布式一致性</span>
                            </a>
                        
                            <a href="/tags/Raft/">
                                <span class="chip bg-color">Raft</span>
                            </a>
                        
                            <a href="/tags/%E8%AF%91%E6%96%87/">
                                <span class="chip bg-color">译文</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" class="post-category">
                                分布式
                            </a>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/" class="post-category">
                                一致性协议
                            </a>
                        
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/Raft/" class="post-category">
                                Raft
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-03-04
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.1k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    15 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>翻译自<a target="_blank" rel="noopener" href="https://eli.thegreenplace.net/archives/all">Eli Bendersky</a>的<a target="_blank" rel="noopener" href="https://eli.thegreenplace.net/2020/implementing-raft-part-3-persistence-and-optimizations/">系列博客</a>，已获得原作者授权。</p>
<p>本文是系列文章中的第一部分，本系列文章旨在介绍Raft分布式一致性协议及其Go语言实现。文章的完整列表如下：</p>
<ul>
<li>序言：<a href="/posts/772d24e8.html" title="介绍">介绍</a></li>
<li>第一部分：<a href="/posts/be586517.html" title="选主">选主</a></li>
<li>第二部分：<a href="/posts/25bc8c4b.html" title="指令和日志复制">指令和日志复制</a></li>
<li>第三部分：持久性和优化(本文)</li>
</ul>
<p>在这一部分，我们会添加持久性和一些优化来完善Raft的基础实现。所有代码已上传到<a target="_blank" rel="noopener" href="https://github.com/eliben/raft/tree/master/part3">这个目录</a>。</p>
<h3 id="持久性"><a href="#持久性" class="headerlink" title="持久性"></a>持久性</h3><p>类似Raft这样的一致性算法的目标，就是通过在独立的服务器之间复制任务来创建一个更具高可用性的系统。在此之前，我们主要关注的是<em>网络分区</em>的故障，也就是集群中一些服务器与其它服务器（或客户端）断开了连接。还有另一种失败模式就是<em>崩溃</em>，也就是一台服务器停止工作并重启。</p>
<p>对于其它服务器，这看起来很像网络分区——服务器暂时断开连接，但是对于崩溃服务器自身来说，情况就完全不同了，因为重启之后其内部所有的易失性存储状态都丢失了。</p>
<p>正是由于这个原因，Raft论文中的图2中清楚地标注了哪些状态应该<em>持久化</em>，持久化的状态在每次更新的时候都需要刷新到非易失性存储中。在服务器发起下一次RPC或响应正在进行的RPC之前，所有需要持久化的状态都需要保存好。</p>
<p>Raft可以通过仅持久化其状态的一个子集来实现，也就是：</p>
<ul>
<li><code>currentTerm</code> - 此服务器观察到的最新任期</li>
<li><code>votedFor</code> - 在最新任期中，此服务器投赞同票的服务器ID</li>
<li><code>log</code> - Raft日志条目</li>
</ul>
<p><strong>Q：</strong>为什么<code>commitIndex</code>和<code>lastApplied</code>是易失性的？</p>
<p><strong>A：</strong><code>commitIndex</code>字段是易失性的，因为在重启之后，Raft只根据持久化状态就可以得到正确的值。一旦领导者成功提交了一条新指令，它也就知道在此之前的所有指令都已经提交了。如果一个追随者崩溃又重新接入集群中，当前领导者向其发送AE请求时，会告诉其正确的<code>commitIndex</code>。</p>
<p>重启之后，<code>lastApplied</code>是从0开始的，因为基本的Raft算法假定了服务（如键-值数据库）不会保存任何持久化状态。因此，需要通过重放日志条目来重新创建它的状态。当然，这是相当低效的，也有很多可行的优化方法。Raft支持在日志变大时对其进行<em>快照</em>，这在Raft论文的第6章节有描述，不过这也超出了本系列的讨论范围。</p>
<h3 id="指令传递语义"><a href="#指令传递语义" class="headerlink" title="指令传递语义"></a>指令传递语义</h3><p>在Raft中，根据不同情况，一条指令会多次发给客户端。有几种场景会出现这样的情况，包括崩溃和重启（重放日志恢复服务）。</p>
<p>在消息传递语义方面，Raft站在<em>至少一次</em>阵营。一旦一条指令被呈递，它最终会被复制给所有的客户端，但是有些客户端可能会多次看到同一条指令。</p>
<p>因此，建议指令需要携带唯一的ID，而客户端要忽略已经收到的指令。这个在Raft论文的第8节有更详细的描述。</p>
<h3 id="存储接口"><a href="#存储接口" class="headerlink" title="存储接口"></a>存储接口</h3><p>为了实现持久性，我们在代码中添加了如下的接口：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">type</span> Storage <span class="token keyword">interface</span> <span class="token punctuation">{</span>
  <span class="token function">Set</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">,</span> value <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">)</span>

  <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token builtin">bool</span><span class="token punctuation">)</span>

  <span class="token comment" spellcheck="true">// HasData returns true if any Sets were made on this Storage.</span>
  <span class="token function">HasData</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token punctuation">}</span></code></pre>
<p>你可以将它看作是字符串到通用字节切片的映射，由持久性存储实现。</p>
<h3 id="恢复和保存状态"><a href="#恢复和保存状态" class="headerlink" title="恢复和保存状态"></a>恢复和保存状态</h3><p>现在CM构造函数要接受<code>Storage</code>作为参数并进行调用：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">if</span> cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">HasData</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span><span class="token function">restoreFromStorage</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>storage<span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>这里的<code>restoreFromStorage</code>方法也是新加的，该方法会从存储中加载持久化的状态变量，使用标准的<code>encoding/go</code>包对其进行反序列化：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">restoreFromStorage</span><span class="token punctuation">(</span>storage Storage<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> termData<span class="token punctuation">,</span> found <span class="token operator">:=</span> cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"currentTerm"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> found <span class="token punctuation">{</span>
    d <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewDecoder</span><span class="token punctuation">(</span>bytes<span class="token punctuation">.</span><span class="token function">NewBuffer</span><span class="token punctuation">(</span>termData<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> d<span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"currentTerm not found in storage"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">if</span> votedData<span class="token punctuation">,</span> found <span class="token operator">:=</span> cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"votedFor"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> found <span class="token punctuation">{</span>
    d <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewDecoder</span><span class="token punctuation">(</span>bytes<span class="token punctuation">.</span><span class="token function">NewBuffer</span><span class="token punctuation">(</span>votedData<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> d<span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>cm<span class="token punctuation">.</span>votedFor<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"votedFor not found in storage"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">if</span> logData<span class="token punctuation">,</span> found <span class="token operator">:=</span> cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"log"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> found <span class="token punctuation">{</span>
    d <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewDecoder</span><span class="token punctuation">(</span>bytes<span class="token punctuation">.</span><span class="token function">NewBuffer</span><span class="token punctuation">(</span>logData<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> d<span class="token punctuation">.</span><span class="token function">Decode</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"log not found in storage"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>镜像方法是<code>persistToStorage</code>——将所有的状态变量编码并保存到提供的存储介质中。</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">persistToStorage</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> termData bytes<span class="token punctuation">.</span>Buffer
  <span class="token keyword">if</span> err <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewEncoder</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>termData<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Encode</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"currentTerm"</span><span class="token punctuation">,</span> termData<span class="token punctuation">.</span><span class="token function">Bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

  <span class="token keyword">var</span> votedData bytes<span class="token punctuation">.</span>Buffer
  <span class="token keyword">if</span> err <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewEncoder</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>votedData<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Encode</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>votedFor<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"votedFor"</span><span class="token punctuation">,</span> votedData<span class="token punctuation">.</span><span class="token function">Bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

  <span class="token keyword">var</span> logData bytes<span class="token punctuation">.</span>Buffer
  <span class="token keyword">if</span> err <span class="token operator">:=</span> gob<span class="token punctuation">.</span><span class="token function">NewEncoder</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>logData<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Encode</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span>storage<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"log"</span><span class="token punctuation">,</span> logData<span class="token punctuation">.</span><span class="token function">Bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>我们只需要在这些状态值每次变化时都调用<code>pesistToStorage</code>方法即可实现持久化。如果你比对一下第二部分和本部分的CM代码，就能看的该方法的调用散步在少数几个地方。</p>
<p>当然，这并不是最有效的持久化方式，但是它简单有效，因此也可以满足我们的需要。效率最低的部分是保存整个日志，日志在实际的应用中可能会很大。为了真正解决整个问题，Raft论文的第7节提出了一个<em>日志压缩</em>机制。我们不会实现压缩，但是可以将其作为联系添加到已有的实现中。</p>
<h3 id="崩溃恢复"><a href="#崩溃恢复" class="headerlink" title="崩溃恢复"></a>崩溃恢复</h3><p>实现持久性之后，我们的Raft集群可以在一定程度上应对崩溃。只要是集群中的少数服务器崩溃并在之后的某个时间重启，集群对于客户端都是一直可用的（如果领导者是崩溃的服务器之一，可能还需要等集群选举出新的领导者）。提醒一下，拥有<code>2N+1</code>个服务器的集群可以容忍N台服务器出现故障，并且只要其它<code>N+1</code>台机器保持互连，集群就是一直可用的。</p>
<h3 id="不可靠的RPC传递"><a href="#不可靠的RPC传递" class="headerlink" title="不可靠的RPC传递"></a>不可靠的RPC传递</h3><p>我们在这一部分加强了测试，我想提醒您注意关于系统弹性的另一个方面——不可靠的RPC传递。在此之前，我们都假设在连接的服务器之间的RPC请求都会成功到达，可能会有很小的延时。如果你看一下<code>server.go</code>，你会注意到其中使用了一个<code>RPCProxy</code>类型来实现随机延迟。每个RPC请求会延迟1-5ms，以模拟真实世界中同一数据中心的同伴服务器通信延时。</p>
<p><code>RPCProxy</code>还帮助我们实现了可选的<em>不可靠</em>传递。如果启动了<code>RAFT_UNRELIABLE_RPC</code>系统变量，RPC会偶尔出现明显的延迟（75ms）或者被直接丢弃，用于模拟真实世界中的网络故障。</p>
<p>我们可以设置<code>RAFT_UNRELIABLE_RPC</code>之后运行之前的测试，观察Raft集群在出现这些故障时的行为——另一个强烈推荐的练习。如果您学有余力，可以修改一下<code>RPCProxy</code>，对RPC<em>应答</em>也进行延迟，这应该只需要改几行代码。</p>
<h3 id="优化发送AE"><a href="#优化发送AE" class="headerlink" title="优化发送AE"></a>优化发送AE</h3><p>我在<a href="/posts/25bc8c4b.html" title="第二部分">第二部分</a>提到过，目前领导者的实现效率很低。领导者在<code>leaderSendHeartbeats</code>方法中发送AE请求，而该方法由定时器每50ms触发一次。假设有一天新的指令被呈递，领导者不会立即通知所有的追随者，而是等待下一个50ms的触发。更糟糕的是，要通知追随者某条指令被提交需要通过两次AE请求。下图展示了目前的工作流程：</p>
<p><img src="/posts/9e1d4cec/appendentries-50ms-boundary.png" alt="Timing diagram with AE on 50 ms boundaries"></p>
<p>在时刻1，领导者向追随者发送了一次心跳AE，并在几ms后收到了响应。</p>
<p>之后有一条新指令被提交（假设是35ms后）。</p>
<p>领导者等到下一个50ms计时结束，也就是时刻2再向追随者发送更新后的日志。</p>
<p>在时刻3，追随者回复指令已经成功添加到本地的日志中。此时，领导者已经修改了它的<code>commit index</code>（假定已得到多数服务器确认）并可以立即通知追随者。但是，领导者一直等到下一个50ms边界（时刻4）才这样做。</p>
<p>最后，当追随者收到更新后的<code>leaderCommit</code>时，将最新的提交指令通知到客户端。</p>
<p>我们的实现中，领导者<code>Submit(X)</code>和追随者<code>commitChan &lt;-X</code>之间等待的大部分时间都是不必要的。</p>
<p>我们真正想要的执行顺利应该像下面这样：</p>
<p><img src="/posts/9e1d4cec/appendentries-immediate.png" alt="Timing diagram with AE on 50 ms boundaries"></p>
<p>这正是<a target="_blank" rel="noopener" href="https://github.com/eliben/raft/tree/master/part3">本部分代码</a>所做的。我们先从<code>startLeader</code>开始看一下实现中的新代码：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">startLeader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>state <span class="token operator">=</span> Leader

  <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> peerId <span class="token operator">:=</span> <span class="token keyword">range</span> cm<span class="token punctuation">.</span>peerIds <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">len</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span>matchIndex<span class="token punctuation">[</span>peerId<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span>
  <span class="token punctuation">}</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"becomes Leader; term=%d, nextIndex=%v, matchIndex=%v; log=%v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>nextIndex<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>matchIndex<span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>

  <span class="token comment" spellcheck="true">/*********以下代码是新增部分********/</span>
  <span class="token comment" spellcheck="true">/*
    该goroutine在后台运行并向同伴服务器发送AE请求：
    - triggerAEChan通道发送任何内容时
    - 如果triggerAEChan通道没有内容时，每50ms执行一次
    */</span>
  <span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span>heartbeatTimeout time<span class="token punctuation">.</span>Duration<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// Immediately send AEs to peers.</span>
    cm<span class="token punctuation">.</span><span class="token function">leaderSendAEs</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    t <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">NewTimer</span><span class="token punctuation">(</span>heartbeatTimeout<span class="token punctuation">)</span>
    <span class="token keyword">defer</span> t<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> <span class="token punctuation">{</span>
      doSend <span class="token operator">:=</span> <span class="token boolean">false</span>
      <span class="token keyword">select</span> <span class="token punctuation">{</span>
      <span class="token keyword">case</span> <span class="token operator">&lt;-</span>t<span class="token punctuation">.</span>C<span class="token punctuation">:</span>
        doSend <span class="token operator">=</span> <span class="token boolean">true</span>

        <span class="token comment" spellcheck="true">// Reset timer to fire again after heartbeatTimeout.</span>
        t<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        t<span class="token punctuation">.</span><span class="token function">Reset</span><span class="token punctuation">(</span>heartbeatTimeout<span class="token punctuation">)</span>
      <span class="token keyword">case</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ok <span class="token operator">:=</span> <span class="token operator">&lt;-</span>cm<span class="token punctuation">.</span>triggerAEChan<span class="token punctuation">:</span>
        <span class="token keyword">if</span> ok <span class="token punctuation">{</span>
          doSend <span class="token operator">=</span> <span class="token boolean">true</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
          <span class="token keyword">return</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">// Reset timer for heartbeatTimeout.</span>
        <span class="token keyword">if</span> <span class="token operator">!</span>t<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token operator">&lt;-</span>t<span class="token punctuation">.</span>C
        <span class="token punctuation">}</span>
        t<span class="token punctuation">.</span><span class="token function">Reset</span><span class="token punctuation">(</span>heartbeatTimeout<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>

      <span class="token keyword">if</span> doSend <span class="token punctuation">{</span>
        cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">!=</span> Leader <span class="token punctuation">{</span>
          cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
          <span class="token keyword">return</span>
        <span class="token punctuation">}</span>
        cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        cm<span class="token punctuation">.</span><span class="token function">leaderSendAEs</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token number">50</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Millisecond<span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p><code>startLeader</code>方法中的循环不只是等待50ms的触发器，而且等待两种可能的情况之一：</p>
<ul>
<li><code>cm.triggerAEChan</code>通道上的数据发送</li>
<li>50ms的定时器计时结束</li>
</ul>
<p>我们稍后会看到是什么触发了<code>cm.triggerAEChan</code>，这个信号表示<em>现在</em>要发送一条AE请求。无论何时触发该通道，定时器都会重置，从而实现心跳逻辑——如果领导者没有新信息需要发送，最多会等待50ms。</p>
<p>还要注意，真正发送AE请求的方法名改为了<code>leaderSendAEs</code>，以便更好地反映新代码的设计意图。</p>
<p>如我们所料，触发<code>cm.triggerAEChan</code>的方法之一 就是<code>Submit</code>：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>cm <span class="token operator">*</span>ConsensusModule<span class="token punctuation">)</span> <span class="token function">Submit</span><span class="token punctuation">(</span>command <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"Submit received by %v: %v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>state<span class="token punctuation">,</span> command<span class="token punctuation">)</span>
  <span class="token keyword">if</span> cm<span class="token punctuation">.</span>state <span class="token operator">==</span> Leader <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span>log <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>cm<span class="token punctuation">.</span>log<span class="token punctuation">,</span> LogEntry<span class="token punctuation">{</span>Command<span class="token punctuation">:</span> command<span class="token punctuation">,</span> Term<span class="token punctuation">:</span> cm<span class="token punctuation">.</span>currentTerm<span class="token punctuation">}</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">persistToStorage</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"... log=%v"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>log<span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    cm<span class="token punctuation">.</span>triggerAEChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span>
  <span class="token punctuation">}</span>

  cm<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">return</span> <span class="token boolean">false</span>
<span class="token punctuation">}</span></code></pre>
<p>更改如下：</p>
<ul>
<li>每当收到新指令时，调用<code>cm.persistToStorage</code>对新的日志条目进行持久化。这与心跳请求的优化无关，但是我还是要在这里说明一下，因为第2部分的代码没有实现该功能，而且该功能是在本文的前面描述的。</li>
<li>在<code>cm.persistToStorage</code>上发送空结构体。这会通知领导者goroutine中的循环。</li>
<li>锁处理顺序做了轻微调整。我们不想在使用<code>cm.persistToStorage</code>发送数据时持有锁，因为在某些情况下会导致死锁。</li>
</ul>
<p>你能猜到代码中还有什么地方会通知<code>triggerAEChan</code>吗？</p>
<p>就是在领导者处理AE应答并修改<code>commit index</code>的代码中，我这里就不贴出整个方法，只复制了修改的部分：</p>
<pre class=" language-go"><code class="language-go"> <span class="token keyword">if</span> cm<span class="token punctuation">.</span>commitIndex <span class="token operator">!=</span> savedCommitIndex <span class="token punctuation">{</span>
    cm<span class="token punctuation">.</span><span class="token function">dlog</span><span class="token punctuation">(</span><span class="token string">"leader sets commitIndex := %d"</span><span class="token punctuation">,</span> cm<span class="token punctuation">.</span>commitIndex<span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// Commit index改变：表明领导者认为新指令可以被提交了。</span>
    <span class="token comment" spellcheck="true">// 通过commit channel向领导者的客户端发送新指令。</span>
    <span class="token comment" spellcheck="true">// 发送AE请求通知所有的追随者</span>
    cm<span class="token punctuation">.</span>newCommitReadyChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
    cm<span class="token punctuation">.</span>triggerAEChan <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
  <span class="token punctuation">}</span></code></pre>
<p>这是一个重要的优化，可以让我们的代码对新指令的响应速度更快。</p>
<h3 id="批量化指令提交"><a href="#批量化指令提交" class="headerlink" title="批量化指令提交"></a>批量化指令提交</h3><p>上一节中的代码看起来可能会让你有些不舒服，现在有很多行为是每次调用<code>Submit</code>时触发的——领导者立即向追随者广播RPC请求。如果我们一次提交多条命令时会怎样？连接Raft集群的网络可能被RPC请求淹没。</p>
<p>尽管看起来效率低下，但实际上是安全的。Raft的RPC请求都是幂等的，意味着多次收到包含相同信息的RPC请求不会造成什么危害。</p>
<p>如果你担心同时提交多条指令时导致的网络拥塞，<em>批处理</em>是很容易实现的。最简单的方法就是提供一种将整个指令片段发送给<code>Submit</code>的方式。因此，Raft实现中只有很少的代码需要修改，然后客户端就可以呈递一组指令而不会产生太多RPC通信。作为练习试试看！</p>
<h3 id="优化AE冲突解决"><a href="#优化AE冲突解决" class="headerlink" title="优化AE冲突解决"></a>优化AE冲突解决</h3><p>我想在这篇文章中讨论的另一个优化，是在一些场景中减少领导者更新追随者日志时被拒绝的AE请求数量。回想一下，<code>nextIndex</code>机制从日志的尾端开始，并且每次追随者拒绝AE请求时都减1。在极少数情况下，追随者会出现严重过时，因为每次RPC请求只会回退一条指令索引，所以更新该追随者日志会花费很长时间。</p>
<p>论文在5.3节的最后提到了这种优化，但是没有提供任何的实现细节。为了实现它，我们在AE应答中扩展了新的字段：</p>
<pre class=" language-go"><code class="language-go"><span class="token keyword">type</span> AppendEntriesReply <span class="token keyword">struct</span> <span class="token punctuation">{</span>
  Term    <span class="token builtin">int</span>
  Success <span class="token builtin">bool</span>

  <span class="token comment" spellcheck="true">// Faster conflict resolution optimization (described near the end of section</span>
  <span class="token comment" spellcheck="true">// 5.3 in the paper.)</span>
  ConflictIndex <span class="token builtin">int</span>
  ConflictTerm  <span class="token builtin">int</span>
<span class="token punctuation">}</span></code></pre>
<p>你可以在本部分的代码中看到其它改动。有两个地方做了改动：</p>
<ul>
<li><code>AppendEntries</code>是AE请求处理方法，当追随者拒绝AE请求时，会填入<code>ConflictIndex</code>和<code>ConflictTerm</code>。</li>
<li><code>leaderSendAEs</code>方法在收到AE应答时进行更新，并通过<code>ConflictIndex</code>和<code>ConflictTerm</code>更有效地回溯<code>nextIndex</code>。</li>
</ul>
<p>Raft论文中写：</p>
<blockquote>
<p>在实践中，我们怀疑这种优化是否必要，因为失败很少发生，而且不大可能有很多不一致的条目。</p>
</blockquote>
<p>我完全同意。为了测试这个优化点，我不得不想出一个相当刻意的测试。恕我直言，在现实生活中出现这种情况的概率非常低，而且一次性节省几百ms并不能保证代码复杂度。我在这里只是将它作为Raft中特殊情况下的优化案例之一。就编程而言，这是一个很好的例子，说明在某些特定情况下，可以对Raft算法进行轻微修改来调整其行为逻辑。</p>
<p>Raft的设计意图是保证在普通情况下有相当快的处理速度，并且以牺牲特殊情况下的性能为代价（实际发生故障的情况）。我相信这是绝对正确的设计选择。在上一节中说到的快速发送AE请求优化是很有必要的，因为这会直接影响公共路径。</p>
<p>另一方面，像快速回溯冲突索引这样的优化，虽然在技术上很有趣，但是在实践中并不重要，因为它们只是在集群生命周期中出现时间<code>&lt;0.01%</code>的特殊场景中做出了有限的优化。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>至此，我们结束了有关Raft分布式一致性算法的4篇文章，感谢阅读！</p>
<p>如果您对于文章内容或代码有任何问题，可以给我发送邮件或者在<a target="_blank" rel="noopener" href="https://github.com/eliben/raft/issues">Github</a>发布issue。</p>
<p>如果您对工业级、有实战经验的Raft实现感兴趣，我向您推荐：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://github.com/etcd-io/etcd/tree/master/raft">etcd/raft</a>是分布式键值数据库etcd中的Raft模块。</li>
<li><a target="_blank" rel="noopener" href="https://github.com/hashicorp/raft">hashicorp/raft</a>是一个独立的Raft一致性模块，可以帮到到不同的客户端。</li>
</ul>
<p>它们都实现了Raft论文中的所有特性，包括：</p>
<ul>
<li>Section 6： 集群成员关系变动——如果一台Raft服务器永久离线，在不关闭集群的情况下使用另一台服务器对其替换是很实用的。</li>
<li>Section 7：日志压缩——在实际的应用程序中，日志会变得非常大，每次修改都完全持久化日志或者在崩溃时完全重放日志都是很不切实际的。日志压缩定义了一种检查点机制，该机制使得集群可以有效复制非常大的日志。</li>
</ul>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Guo Yaxiang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.codinghonest.space/posts/9e1d4cec.html">https://www.codinghonest.space/posts/9e1d4cec.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Guo Yaxiang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                                    <span class="chip bg-color">分布式一致性</span>
                                </a>
                            
                                <a href="/tags/Raft/">
                                    <span class="chip bg-color">Raft</span>
                                </a>
                            
                                <a href="/tags/%E8%AF%91%E6%96%87/">
                                    <span class="chip bg-color">译文</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    
        <style>
    .mvaline-card {
        margin: 1.5rem auto;
    }

    .mvaline-card .card-content {
        padding: 20px 20px 5px 20px;
    }
</style>

<div class="card mvaline-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="mvcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/minivaline/MiniValine.js"></script>
<script>
    new MiniValine({
        el: '#mvcomments',
        appId: 'oqAo7rCWejwTqHjGC2APTVDX-MdYXbMMI',
        appKey: 'pfyY919tO7iJaDm7lFmvh5Wp',
        mode: 'DesertsP',
        placeholder: 'Write a Comment',
        pathname: window.location.pathname,
        lang: '',
        adminEmailMd5: '8BBC105436DAAF8C803841C8FD13CD0C',
        tagMeta: ["管理员", "小伙伴", "访客"],
        master: ["8BBC105436DAAF8C803841C8FD13CD0C"],
        friends: ["FA21C7921CD42FE9523E957870873F64", "586BAB41BB5692877F7714DFE4947DEC"],
        math: true,
        md: true,
        enableQQ: false,
        NoRecordIP: false,
        visitor: true,
        maxNest: 6,
        pageSize: 6,
        serverURLs: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest", "https://cdn.jsdelivr.net/gh/MiniValine/qq@latest", "https://cdn.jsdelivr.net/gh/MiniValine/Bilibilis@latest", "https://cdn.jsdelivr.net/gh/MiniValine/tieba@latest", "https://cdn.jsdelivr.net/gh/MiniValine/twemoji@latest", "https://cdn.jsdelivr.net/gh/MiniValine/weibo@latest"],
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/dc1362d2.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="响应式系统中的背压">
                        
                        <span class="card-title">响应式系统中的背压</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            这篇文章是关于反压力的简单介绍，并讲述了RxJava (v3)、Project Reactor和Kotlin的协程中是如何处理它的。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-04-20
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            <a href="/categories/Java/Reactive-Stream/" class="post-category">
                                    Reactive Stream
                                </a>
                            
                            <a href="/categories/Java/Reactive-Stream/%E5%93%8D%E5%BA%94%E5%BC%8F/" class="post-category">
                                    响应式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java-Stream/">
                        <span class="chip bg-color">Java Stream</span>
                    </a>
                    
                    <a href="/tags/Reactive-Stream/">
                        <span class="chip bg-color">Reactive Stream</span>
                    </a>
                    
                    <a href="/tags/%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BC%96%E7%A8%8B/">
                        <span class="chip bg-color">响应式编程</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/25bc8c4b.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="实现Raft协议：Part 2 - 指令和日志复制">
                        
                        <span class="card-title">实现Raft协议：Part 2 - 指令和日志复制</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本系列文章的写作目的，在于描述Raft协议的一个功能完备且经过严格测试的实现方式，并提供一些Raft工作方式的直观理解。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-03-04
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/" class="post-category">
                                    分布式
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/" class="post-category">
                                    一致性协议
                                </a>
                            
                            <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/%E4%B8%80%E8%87%B4%E6%80%A7%E5%8D%8F%E8%AE%AE/Raft/" class="post-category">
                                    Raft
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%B8%80%E8%87%B4%E6%80%A7/">
                        <span class="chip bg-color">分布式一致性</span>
                    </a>
                    
                    <a href="/tags/Raft/">
                        <span class="chip bg-color">Raft</span>
                    </a>
                    
                    <a href="/tags/%E8%AF%91%E6%96%87/">
                        <span class="chip bg-color">译文</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 码道诚公<br />'
            + '文章作者: Guo Yaxiang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Guo Yaxiang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/GuoYaxiang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:YXGyxg112358@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1431800679" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1431800679" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/guo-ya-xiang" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/guo-ya-xiang" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    
        <script src="//code.tidio.co/zgiqinzrat1rzwxseqhr2pnzsp2a4rjo.js"></script>
        <script>
            $(document).ready(function () {
                setInterval(change_Tidio, 50);
                function change_Tidio() {
                    var tidio=$("#tidio-chat iframe");
                    if(tidio.css("display")=="block"&& $(window).width()>977 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"85px":"20px";
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                        document.getElementById("tidio-chat-iframe").style.zIndex="998";
                    }
                }
            });
        </script>
    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
